﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCPets.Models;
using MVCPets.Helpers;
using System.Drawing;
using MVCPets.Extensions;

namespace MVCPets.Controllers
{
  public class PetManagementController : BaseController
  {
    #region Security
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
      base.Initialize(requestContext);

      if (SessionHelper.UserRole <= RoleHelper.GetRoleValue("Contributor")) Return404();
    }
    #endregion

    #region Index
    [HttpGet]
    public ActionResult Index()
    {
      return RedirectToAction("Index", "Pets");
    }
    #endregion

    #region Details
    [HttpGet]
    public ActionResult Details(int id)
    {
      return RedirectToAction("Details", "Pets", new { id = id });
    }
    #endregion

    #region Create
    [HttpGet]
    public ActionResult Create()
    {
      return View(new PetsModel());
    }

    [HttpPost, ValidateInput(false)]
    public ActionResult Create(PetsModel model)
    {
      var image = Request.Files[0];
      
      if(image != null)
      {
        model.ThumbnailType = image.ContentType;
        model.ThumbnailData = image.InputStream.ToByteArray();
      }

      if (model.Save()) return RedirectToAction("Index", "Pets");
      else return View(model);
    }
    #endregion

    #region Edit
    [HttpGet]
    public ActionResult Edit(Guid id)
    {
      return View(new PetsModel(id));
    }

    [HttpPost, ValidateInput(false)]
    public ActionResult Edit(PetsModel model)
    {
      if (model.Save()) return RedirectToAction("Index", "Pets");
      else return View(model);
    }
    #endregion

    #region Delete
    [HttpGet]
    public ActionResult Delete(Guid id)
    {
      return View(new PetsModel(id));
    }

    [HttpPost]
    public ActionResult Delete(PetsModel model)
    {
      if(model.Delete()) return RedirectToAction("Index", "Pets");
      else return View(model);
    }
    #endregion
  }
}
